#include "union_module.h"
#include "../share/MessageDef.h"
#include "../share/retcodes.h"
#include "../share/jsonmessage.h"
#include "Fixed1024.h"
#include "GameServer.h"
#include "playerinfo_mgr.h"
#include "../share/proxyclient_service.h"
#include "message_code.h"
#include "scene_logic.h"
#include "MapSlot.h"
#include "script_define.h"
#include "scene_event.h"
#include "../share/tplmgr.h"
#include "scene_event.h"
#include "../share/time_module.h"
#include "activity_module.h"
#include "PlayerLevelUpCacheData.h"
#include "ManagerHelper.h"


void CUnionModule::Initialize()
{
	registe_client_msg(union_query_union_list_req, CUnionModule::queryCurrentUnionListRequest);
	registe_client_msg(union_create_someone_req, CUnionModule::createUnionRequest);
	registe_client_msg(union_search_someone_req, CUnionModule::searchUnionRequest);
	registe_client_msg(union_disband_someone_req, CUnionModule::disbandUnionRequest);
	registe_client_msg(union_application_join_req, CUnionModule::applicationJoinSomeUnionRequest);
	registe_client_msg(union_query_application_list_req, CUnionModule::queryApplicationJoinUnionListRequest);
	registe_client_msg(union_approve_application_req, CUnionModule::approveSomeoneApplicationJoinUnionRequest);
	registe_client_msg(union_exits_someone_req, CUnionModule::exitsSomeoneUnionRequest);
	registe_client_msg(union_kickout_someone_req, CUnionModule::kickoutUnionSomeoneRequest);
	registe_client_msg(union_change_someone_position_req, CUnionModule::changeUnionSomeonePositionRequest);
	registe_client_msg(union_query_all_member_req, CUnionModule::queryUnionAllMemberRequest);
	registe_client_msg(union_edit_some_info_req, CUnionModule::editUnionSomeInformationRequest);
	registe_client_msg(union_query_detailed_info_req, CUnionModule::queryUnionDeatiledInformationRequest);
	registe_client_msg(union_query_journal_list_req, CUnionModule::queryUnionJournalListRequest);
	registe_client_msg(union_player_donation_req, CUnionModule::playerUnionDonationRequest);
	registe_client_msg(union_player_donation_info_req, CUnionModule::playerUnionDonationInfoRequest);
	registe_client_msg(union_uplevel_info_req, CUnionModule::playerUnionUpLevelRequest);
	registe_client_msg(id_c2g_player_cancel_apply_request, CUnionModule::PlayerCancelApplyRequest);

	// 公会boss相关
	registe_client_msg(union_enter_boss_request, CUnionModule::PlayerEnterUnionBossRequest);
	registe_client_msg(union_boss_damage_report, CUnionModule::PlayerDamageReport);
	registe_client_msg(union_boss_info_request, CUnionModule::UnionBossInfoRequest);

	//酒馆
	registe_client_msg(union_alcohol_list_req, CUnionModule::QueryUnionAlcoholList);
	registe_client_msg(union_alcohol_use_req, CUnionModule::UseUnionAlcohol);

	// 工会红包
	registe_client_msg(union_query_redpacket_list_req, CUnionModule::queryUnionRedpacketListRequest);
	registe_client_msg(union_get_redpacket_req, CUnionModule::playerGetRedpacketRequest);
	registe_client_msg(union_query_redpacket_info_req, CUnionModule::queryUnionRedpacketInfoRequest);
	registe_client_msg(union_send_redpacket_req, CUnionModule::playerSendRedpacketRequest);

	//player_union_data_change += CUnionModule::OnPlayerUnionDataChange;

	CGuildManager::GetInstance().Initialize();
	activity_start_event += OnActivityStart;
	activity_end_event += OnActivityEnd;
	player_enter_game_event += OnPlayerEnterGame;
}

void CUnionModule::Finalize()
{
	//player_union_data_change -= CUnionModule::OnPlayerUnionDataChange;

	activity_start_event -= OnActivityStart;
	activity_end_event -= OnActivityEnd;
	player_enter_game_event -= OnPlayerEnterGame;

	CGuildManager::GetInstance().Finalize();
	CGuildManager::ReleaseInstance();
}

// ----------------------------------------------------------------------------
//获取已创建公会列表 9776 *
//playerId
// account
// count->arg1 指定搜索数量
// start->arg2 指定搜索开始
// union_query_union_list_ret = 0x630;
//union_query_union_list_req = server_start + union_query_uncion_list_ret;
//ret : {ret = 0, desc = "", item = 
//{ { ui = 公会ID,un = 公会名称,mo = 公会宣言,ic = 公会旗帜,ci = 会长ID,cn = 会长昵称,lv = 公会等级,ct = 创建时间 }..{} }, 
//auj = { 已申请公会ID,已申请公会ID,已申请公会ID }}
// ----------------------------------------------------------------------------
void CUnionModule::queryCurrentUnionListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t count = m_jv["arg1"].asInt();
	int32_t start = m_jv["arg2"].asInt();
	if (count == 0)
	{
		count = 10;
	}
	Json::Value response;
	response["msgid"] = union_query_union_list_ret;
	response["ret"] = ::common::SUCCEED;
	Json::Value item;
	CGuildManager::GetInstance().FillGuildToJson(item, start, count);
	response["item"] = item;
	Json::Value auj;
	CGuildManager::GetInstance().GetPlayerApplyList(auj, player.GetPlayerId());
	response["auj"] = auj;
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(player.GetPlayerId());
	if ( playerinfo != NULL )
	{
		response["jointime"] = playerinfo->PlayerGuild().GetJoinCDLimitTime();
	}
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_union_list_ret);
}

// ----------------------------------------------------------------------------
//创建公会 9778 *
//playerId
// account
// name->arg1
// desc->arg2
// icon->arg3
// groupId->arg4
// union_create_someone_ret = 0x632;
//union_create_someone_req = server_start + union_create_someone_ret;
// ----------------------------------------------------------------------------
void CUnionModule::createUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	std::string name = m_jv["arg1"].asString();
	std::string desc = m_jv["arg2"].asString();
	std::string icon = m_jv["arg3"].asString();
	int32_t minlv = m_jv["minlv"].asInt();
	int32_t auto_join = m_jv["autojoin"].asInt();

	if ( minlv < 0 || minlv > 50 )
	{
		minlv = 0;
	}

	Json::Value response;
	response["msgid"] = union_create_someone_ret;
	response["ret"] = ::common::SUCCEED;
	// 判断有没有公会
	if (player.GetUnionId() != 0)
	{
		response["ret"] = ::common::ERR_UNION_HAS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_create_someone_ret);
		return;
	}
 	int32_t ret = CUnionModule::GetInstance().CanPlayerJoinUnionCD(player.GetPlayerId());
	if (ret != ::common::SUCCEED)
	{
		response["ret"] = ret;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_create_someone_ret);
		return;
	}

	// 公会名称已经存在
	CGuild* guild = CGuildManager::GetInstance().GetGuildByName(name);
	if (NULL != guild)
	{
		response["ret"] = ::common::ERR_NAME_REPEAT;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_create_someone_ret);
		return;
	}
	// 判断消耗
	if (player.GetCurrency(Fixed1024::CURRENCY_DIAMOND) < 400)
	{
		response["ret"] = ::common::ERR_CREATE_UNION_DIAMOND_LESS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_create_someone_ret);
		return;
	}

	// 先消耗钻石，再创建公会
	ret = player.ChangeNumber(Fixed1024::CURRENCY_DIAMOND, 400);
	if (ret != ::common::SUCCEED)
	{
		LOG_ERROR("default","change number err player[%d] ret[%d]", player.GetPlayerId(), ret);
		response["ret"] = ::common::ERR_CREATE_UNION_CONSUME_DIAMOND_ERR;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_create_someone_ret);
		return;
	}

	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(player.GetPlayerId());
	if (playerinfo == NULL)
	{
		LOG_ERROR("default","create union err player info is null [%d]", player.GetPlayerId());
		return;
	}
	guild = CGuildManager::GetInstance().CreateGuild(name, icon, *playerinfo, desc, minlv, auto_join);
	if (guild == NULL)
	{
		LOG_ERROR("default","create union err guild is null playerid[%d]", player.GetPlayerId());
		return;
	}

	response["ret"] = ::common::SUCCEED;
	response["unionId"] = guild->get_guild_id();
	response["unionName"] = guild->get_name();
	response["unionPosition"] = player.GetUnionPosition();
	response["diamond"] = player.GetCurrency(Fixed1024::CURRENCY_DIAMOND);

	guild->AddGuildLog(player.GetPlayerId(), 0, ELog_Create);

	// 发送到db存储一下
	Json::Value guild_data;
	guild->SaveToJson(guild_data);
	Json::Value db_request;
	db_request["guild_data"] = guild_data;
	std::string db_str = JsonWriter(db_request);
	send_2_db(id_g2d_create_guild_request, db_str, 0);

	std::string sendstr = JsonWriter(response);
	player.SendToClient(&sendstr, union_create_someone_ret);

	//全服通知
	//CMsgCode::SendMsgCodeToAllPlayer(::common::INFO_UNION_CREATE_CONGI, std::string(player.GetName()), guild->get_name());
	
	// 执行后续lua逻辑
	Json::Value table_param;
	table_param["playerId"] = player.GetPlayerId();
	std::string str = JsonWriter(table_param);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
		LUA_UnionEvent, ELua_CreateUnion, str.c_str());
}


// ----------------------------------------------------------------------------
//搜索公会 9777 *
//playerId
// account
// unionId->arg1
// types->arg2 1按公会ID搜索 2按公会名称搜索
//
//union_search_someone_ret = 0x631;
//union_search_someone_req = server_start + union_search_someone_ret;
// ----------------------------------------------------------------------------
void CUnionModule::searchUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	std::string unionName = m_jv["arg1"].asString();
	//1按公会ID搜索 2按公会名称搜索
	int32_t types = m_jv["arg2"].asInt();

	Json::Value response;
	response["msgid"] = union_search_someone_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByName(unionName);
	if (guild != NULL)
	{
		Json::Value guild_info;
		guild_info.clear();
		guild->GuildInfo2Json(guild_info);
		response["item"] = guild_info;
		response["count"] = 1;
	}
	else
	{
		response["ret"] = ::common::ERR_NOT_FOUND_VALID_UNION_INFO;
		response["count"] = 0;
	}
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_search_someone_ret);
}

// ----------------------------------------------------------------------------
//解散公会 9779 *
//playerId
// account
//
//union_disband_someone_ret = 0x633;
//union_disband_someone_req = server_start + union_disband_someone_ret;
// ----------------------------------------------------------------------------
void CUnionModule::disbandUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();

	Json::Value response;
	response["msgid"] = union_disband_someone_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_disband_someone_ret);
		return;
	}
	//判断发起人公会权限等级
	if (player.GetUnionPosition() != E_GUILD_TITLE_CHAIRMAN)
	{
		response["ret"] = ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_disband_someone_ret);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL  )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_disband_someone_ret);
		return;
	}
	if ( guild->member_map().size() != 1 )
	{
		response["ret"] = ::common::ERR_GUILD_CANT_DISBAND;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_disband_someone_ret);
		return;
	}
	CGuildManager::GetInstance().DissolveGuild(player.GetUnionId());
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_disband_someone_ret);

	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(player.GetPlayerId());
	if ( playerinfo != NULL)
	{
		playerinfo->PlayerGuild().set_leave_guild_time(CUR_SEC);
		CPlayerInfoMgr::GetInstance().PlayerChanged(player.GetPlayerId());
	}
}

// ----------------------------------------------------------------------------
//申请加入公会 9780 *
//playerId
// account
// unionId->arg1
//
//union_application_join_ret = 0x634;
//union_application_join_req = server_start + union_application_join_ret;
// ----------------------------------------------------------------------------
void CUnionModule::applicationJoinSomeUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t unionId = m_jv["arg1"].asInt();

	Json::Value response;
	response["msgid"] = union_application_join_ret;
	response["ret"] = ::common::SUCCEED;
	response["unionId"] = unionId;

	if (player.GetUnionId() != 0)
	{
		response["ret"] = ::common::ERR_UNION_HAS_YET;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}
 	int32_t ret = CUnionModule::GetInstance().CanPlayerJoinUnionCD(player.GetPlayerId());
	if ( ret != ::common::SUCCEED )
	{
		response["ret"] = ret;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}

	if (unionId <= 0)
	{
		CUnionModule::GetInstance().PlayerFastApplyJoinUnion(player);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(unionId);
	if (NULL == guild)
	{
		response["ret"] = ::common::ERR_GUILD_NOT_EXIST;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}
	if (guild->IsGuildFull())
	{
		response["ret"] = ::common::ERR_IS_LIMIT_MEMBERS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}
	if ( player.GetLevel() < guild->minlimitlv() )
	{
		response["ret"] = ::common::ERR_GUILD_APPLY_LEVEL_LESS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}

	// 自动加入公会
	if ( guild->auto_join() && !guild->IsGuildFull())
	{
		int32_t ret_code = CGuildManager::GetInstance().autoApply(*guild, player.GetPlayerId());
		if ( ret_code == ::common::SUCCEED )
		{
			// 成功了直接就退出了，失败了，还是走申请逻辑吧
			return;
		}
	}

	int32_t ret_code = CGuildManager::GetInstance().ApplyGuild(player.GetPlayerId(), *guild);
	if (ret_code != ::common::SUCCEED)
	{
		response["ret"] = ret_code;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_application_join_ret);
		return;
	}
	Json::Value auj;
	CGuildManager::GetInstance().GetPlayerApplyList(auj, player.GetPlayerId());
	response["auj"] = auj;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_application_join_ret);

	Json::Value table_param;
	table_param["playerId"] = player.GetPlayerId();
	table_param["unionId"] = unionId;
	std::string str = JsonWriter(table_param);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
		LUA_UnionEvent, Elua_ApplicationJoin, str.c_str());
}

// ----------------------------------------------------------------------------
//获取公会申请列表 9781 *
//playerId
// account
//
//union_query_application_list_ret = 0x635;
//union_query_application_list_req = server_start + union_query_application_list_ret;
// ----------------------------------------------------------------------------
void CUnionModule::queryApplicationJoinUnionListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();

	Json::Value response;
	response["msgid"] = union_query_application_list_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_application_list_ret);
		return;
	}

	// 判断权限
	if (player.GetUnionPosition() != E_GUILD_TITLE_CHAIRMAN)
	{
		response["ret"] = ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_application_list_ret);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		LOG_ERROR("default","guild is null playerid[%d] unionid[%d]", player.GetPlayerId(), player.GetUnionId());
		return;
	}

	Json::Value item;
	guild->FillApplyList(item);
	response["item"] = item;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_application_list_ret);
}

// ----------------------------------------------------------------------------
//批准某人进入公会 9782 *
//playerId
// account
// destId->arg1
// types->arg2    1同意 2拒绝
// union_approve_application_ret = 0x636;
//union_approve_application_req = server_start + union_approve_application_ret;
// ----------------------------------------------------------------------------
void CUnionModule::approveSomeoneApplicationJoinUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t destId = m_jv["arg1"].asInt();
	int32_t types = m_jv["arg2"].asInt();

	Json::Value response;
	response["msgid"] = union_approve_application_ret;
	response["ret"] = 0;

	if (types != 1 && types != 2)
	{
		response["ret"] = ::common::ERR_GUILD_OPERATOR_ERR;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_approve_application_ret);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_approve_application_ret);
		return;
	}
	if (player.GetUnionPosition() == E_GUILD_TITLE_MEMBER)
	{
		response["ret"] = ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_approve_application_ret);
		return;
	}
	int32_t ret_code = CGuildManager::GetInstance().ReplyApply(player, destId, types == 1);

	response["ret"] = ret_code;
	response["type"] = types;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_approve_application_ret);

	CGuildManager::GetInstance().ApplyListNotify(*guild, player.GetPlayerId());
	// 执行后续lua逻辑
	if ( ret_code == ::common::SUCCEED)
	{
		guild->AddGuildLog(player.GetPlayerId(), destId, ELog_Join);
		Json::Value table_param;
		table_param["playerId"] = destId;
		table_param["unionId"] = guild->get_guild_id();
		std::string str = JsonWriter(table_param);
		if (types == 1)
		{
			MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
				LUA_UnionEvent, ELua_JoinUnion, str.c_str());
		}else if(types == 2)
		{
			MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
				LUA_UnionEvent, Elua_ApplicationRefuse, str.c_str());
		}
	}
}

void CUnionModule::exitsSomeoneUnionRequest(Player& player, const CJsonMessageBase& msg)
{
	Json::Value response;
	response["msgid"] = union_exits_someone_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_exits_someone_ret);
		return;
	}

	if (player.GetUnionPosition() == E_GUILD_TITLE_CHAIRMAN)
	{
		response["ret"] = ::common::ERR_UNION_OUT_FIRST_CHANGE_YOUR_ROLE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_exits_someone_ret);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (NULL == guild)
	{
		LOG_ERROR("default","player: %d not in guild: %d", player.GetPlayerId(), player.GetUnionId());
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_exits_someone_ret);
		return;
	}
	int32_t ret_code = CGuildManager::GetInstance().LeaveGuild(*guild, player.GetPlayerId());
	response["ret"] = ret_code;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_exits_someone_ret);
}

void CUnionModule::kickoutUnionSomeoneRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t destId = m_jv["arg1"].asInt();

	Json::Value response;
	response["msgid"] = union_kickout_someone_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (NULL == guild)
	{
		LOG_ERROR("default","gate_role: %d not in guild: %d", player.GetPlayerId(), player.GetUnionId());
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_kickout_someone_ret);
		return;
	}
	if ( player.GetPlayerId() == destId )
	{
		response["ret"] = ::common::ERR_GUILD_KICK_SELF;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_kickout_someone_ret);
		return;
	}
	int32_t ret_code = CGuildManager::GetInstance().KickoutGuild(*guild, player.GetPlayerId(), destId);

	response["ret"] = ret_code;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_kickout_someone_ret);

	if ( ret_code == ::common::SUCCEED)
	{
		CPlayerInfo* dest_playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(destId);
		if (dest_playerinfo != NULL)
		{
			guild->AddGuildLog(player.GetPlayerId(), destId, ELog_Kick);
			// 执行后续lua逻辑
			Json::Value table_param;
			table_param["playerId"] = destId;
			table_param["name"] = dest_playerinfo->get_name();
			table_param["unionName"] = guild->get_name();
			std::string str = JsonWriter(table_param);
			MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
				LUA_UnionEvent, ELua_KickOut, str.c_str());
		}
	}
}

// ----------------------------------------------------------------------------
//公会会长传位给某人 9785 *
//playerId
// account
// destId->arg1 目标ID
//
//union_change_someone_position_ret = 0x639;
//union_change_someone_position_req = server_start + union_change_someone_position_ret;
// ----------------------------------------------------------------------------
void CUnionModule::changeUnionSomeonePositionRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t destId = m_jv["arg1"].asInt();
	int32_t pos = m_jv["pos"].asInt();

	Json::Value response;
	response["msgid"] = union_change_someone_position_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_change_someone_position_ret);
		return;
	}
	if (player.GetUnionPosition() != E_GUILD_TITLE_CHAIRMAN)
	{
		response["ret"] = ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_change_someone_position_ret);
		return;
	}

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (NULL == guild)
	{
		LOG_ERROR("default","Can not find guild: %d", player.GetUnionId());
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_change_someone_position_ret);
		return;
	}
	CGuildMember* member_player = guild->GetMember(player.GetPlayerId());
	if (NULL == member_player)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_change_someone_position_ret);
		return;
	}
	// 不能对自己操作
	if ( player.GetPlayerId() == destId )
	{
		response["ret"] = ::common::ERR_GUILD_CHANGE_SELF_POS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_change_someone_position_ret);
		return;
	}

	int32_t ret_code = guild->AppointTitle(*member_player, destId, pos);
	response["ret"] = ret_code;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_change_someone_position_ret);

	// 执行后续lua逻辑
	if ( ret_code == ::common::SUCCEED )
	{
		guild->AddGuildLog(player.GetPlayerId(), destId, ELog_ChangePos, pos);
		Json::Value table_param;
		table_param["playerId"] = destId;
		table_param["pos"] = pos;
		std::string str = JsonWriter(table_param);
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
			LUA_UnionEvent, ELua_ChangePos, str.c_str());
	}
}

// ----------------------------------------------------------------------------
//获取当前公会会员列表 9786 *
//playerId
// account
// unionId->arg1 公会ID，此数值为空则显示查询人所在公会信息
//
//union_query_all_member_ret = 0x63a;
//union_query_all_member_req = server_start + union_query_all_member_ret;
// ----------------------------------------------------------------------------
void CUnionModule::queryUnionAllMemberRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	Json::Value response;
	response["msgid"] = union_query_all_member_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_all_member_ret);
		return;
	}

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_all_member_ret);
		return;
	}
	Json::Value item;
	guild->FillMemberList(item);
	response["item"] = item;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_all_member_ret);
}

void CUnionModule::OnPlayerUnionDataChange(int32_t playerid, int32_t unionid, std::string unionname, int32_t unionpos, int32_t change_type)
{
	// 玩家在线更新玩家内存数据，redis数据
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerid);
	if (player != NULL)
	{
		// 更新C++中的数据
		player->SetUnionId(unionid);
		player->SetUnionName(unionname.c_str());
		player->SetUnionPosition(unionpos);

		// 通知玩家
		player->SendPlayerUnionInfoChangedNotifyToClient(change_type, unionid, unionpos, unionname);
	}

	// 更新一下lua里redis数据
	CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerid, "unionId", unionid);
	CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerid, "unionName", unionname, 0);
	CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerid, "unionPosition", unionpos);
	if ( unionid == 0 )
	{
		// 公会币清0
		CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerid, "unionCoin", 0);
	}

	// 更新playerinfo中数据
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerid);
	if (playerinfo != NULL)
	{
		playerinfo->set_union_id(unionid);
		playerinfo->set_union_name(unionname);
		playerinfo->set_union_pos(unionpos);
	}
}

// ----------------------------------------------------------------------------
//编辑公会信息 9787 *
//playerId
// account
// unionId->arg1 公会ID
// motto->arg2 公会宣言
// icon->arg3 公会旗帜 暂无用
//
//union_edit_some_info_ret = 0x63b;
//union_edit_some_info_req = server_start + union_change_some_info_ret;
// ----------------------------------------------------------------------------
void CUnionModule::editUnionSomeInformationRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	std::string motto = m_jv["arg2"].asString();
	std::string icon = m_jv["arg3"].asString();
	int32_t minlv = m_jv["minlv"].asInt();
	int32_t auto_join = m_jv["autojoin"].asInt();

	Json::Value response;
	response["msgid"] = union_edit_some_info_ret;
	response["ret"] = ::common::SUCCEED;

	if (player.GetUnionId() == 0)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_edit_some_info_ret);
		return;
	}
	if (player.GetUnionPosition() == E_GUILD_TITLE_MEMBER)
	{
		response["ret"] = ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_edit_some_info_ret);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_edit_some_info_ret);
		return;
	}
	if (minlv < 0 || minlv > 50)
	{
		minlv = 0;
	}
	guild->set_dec(motto);
	guild->set_icon(icon);
	std::string oldname = guild->get_name();
	guild->set_minlv(minlv);
	guild->set_auto_join(auto_join);

	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_edit_some_info_ret);
}


// ----------------------------------------------------------------------------
//获取某公会详细信息 9788
//playerId
// account
// unionId->arg1 公会ID，此数值为空则显示查询人所在公会信息
//
//union_query_detailed_info_ret = 0x63c;
//union_query_detailed_info_req = server_start + union_query_detailed_info_ret;
// ----------------------------------------------------------------------------
void CUnionModule::queryUnionDeatiledInformationRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t destunionId = 0;
	if (m_jv.isMember("arg1"))
	{
		destunionId = m_jv["arg1"].asInt();
	}

	Json::Value response;
	response["msgid"] = union_query_detailed_info_ret;
	response["ret"] = ::common::SUCCEED;


	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_FOUND_VALID_UNION_INFO;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_detailed_info_ret);
		return;
	}
	guild->GuildInfo2Json(response);
	Json::Value item;
	guild->FillMemberList(item);
	response["item"] = item;
	Json::Value my;
	my["playerId"] = player.GetPlayerId();
	my["name"] = player.GetName();
	my["heroId"] = player.GetHeroId();
	my["level"] = player.GetLevel();
	my["heroSkinId"] = player.GetHeroSkinId();
	my["unionPosition"] = player.GetUnionPosition();
	response["my"] = my;

	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_detailed_info_ret);
}


// ----------------------------------------------------------------------------
//公会捐献 9791
//playerId
// account
// unionId->arg1 公会ID
// types->arg2 类型 1金币捐献 2钻石捐献
// union_player_donation_ret = 0x64a;
//union_player_donation_req = server_start + union_query_donation_ret;
// ----------------------------------------------------------------------------
void CUnionModule::playerUnionDonationRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t types = m_jv["arg2"].asInt();

	Json::Value response;
	response["msgid"] = union_player_donation_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}
	CGuildMember* guildMember = guild->GetMember(player.GetPlayerId());
	if ( guildMember == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}
	
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild->get_guilde_lv());
	if ( union_lv == NULL )
	{
		response["ret"] = ::common::ERR_GOT_UNION_INFO_FAIL;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}
	int32_t ret = ::common::SUCCEED;
	if ( types == EGoldDonation )
	{
		ret = guild->GoldDonation(player);
	}
	else if ( types == EDiamondDonation )
	{
		ret = guild->DiamonDonation(player);
	}
	else if (types == ETicketDonation)
	{
		ret = guild->TicketDonation(player);
	}
	else
	{
		ret = ::common::ERR_GUILD_DONATION_TYPE_ERR;
	}

	if ( ret != ::common::SUCCEED )
	{
		response["ret"] = ret;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}

	response["bgt"] = guildMember->gold_donationcount();
	response["bat"] = guildMember->diamod_donationcount();
	response["bct"] = guildMember->ticket_donationcount();
	response["lv"] = guild->get_guilde_lv();
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_player_donation_ret);

	// 处理后续逻辑，去lua
	Json::Value table_param;
	table_param["playerId"] = player.GetPlayerId();
	table_param["unionlv"] = guild->get_guilde_lv();
	table_param["types"] = types;
	table_param["account"] = player.GetAccount();
	std::string str = JsonWriter(table_param);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
		LUA_UnionEvent, ELua_PlayerDonation, str.c_str());
}

void CUnionModule::playerUnionDonationInfoRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();

	Json::Value response;
	response["msgid"] = union_player_donation_info_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_info_ret);
		return;
	}

	CGuildMember* member = guild->GetMember(player.GetPlayerId());
	if ( member == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_info_ret);
		return;
	}

	response["bgt"] = member->gold_donationcount();
	response["bat"] = member->diamod_donationcount();
	response["bct"] = member->ticket_donationcount();
	response["lv"] = guild->get_guilde_lv();
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_player_donation_info_ret);
}

void CUnionModule::playerUnionUpLevelRequest(Player& player, const CJsonMessageBase& msg)
{
	Json::Value response;
	response["msgid"] = union_uplevel_info_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild->get_guilde_lv());
	if (union_lv == NULL)
	{
		response["ret"] = ::common::ERR_GOT_UNION_INFO_FAIL;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}

	int32_t ret = guild->LevelUp(player);
	if ( ret != ::common::SUCCEED )
	{
		response["ret"] = ret;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}

	response["exps"] = guild->get_guild_exp();
	response["level"] = guild->get_guilde_lv();
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_player_donation_ret);

	// 执行后续lua逻辑
	Json::Value table_param;
	table_param["playerId"] = player.GetPlayerId();
	table_param["unionlv"] = guild->get_guilde_lv();
	std::string str = JsonWriter(table_param);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
		LUA_UnionEvent, ELua_UnionLevelUp, str.c_str());
}

void CUnionModule::OnActivityStart(int32_t activityid)
{
	int32_t guildbossid =  CGuildManager::GetInstance().GetGuildBossActivityID();
	if ( activityid == guildbossid)
	{
		LOG_INFO("default", "union activiity start");
		// 公会boss血量每5秒同步一次
		CUnionModule::GetInstance().GetGuildBossTimer().TimerInit(3 * 1000);
		CUnionModule::GetInstance().GetGuildBossTimer().TimerStart();

		CGuildManager::GetInstance().GuildBossStart();
	}
}

void CUnionModule::OnActivityEnd(int32_t activityid)
{
	int32_t guildbossid = CGuildManager::GetInstance().GetGuildBossActivityID();
	if (activityid == guildbossid)
	{
		LOG_INFO("default", "union activiity end");
		// 公会boss血量每5秒同步一次
		CUnionModule::GetInstance().GetGuildBossTimer().TimerStop();
		CGuildManager::GetInstance().GuildBossEnd();
	}
}

void CUnionModule::PlayerCancelApplyRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t unionid = m_jv["unionid"].asInt();// 要取消的工会ID

	Json::Value response;
	response["msgid"] = id_g2c_player_cancel_apply_response;
	response["ret"] = ::common::SUCCEED;
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(unionid);
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_GUILD_CANT_FIND_GUILD;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_player_donation_ret);
		return;
	}
	int32_t ret = guild->CancelApply(player);
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_player_donation_ret);
}

void CUnionModule::PlayerFastApplyJoinUnion(Player& player)
{
	Json::Value response;
	response["msgid"] = union_application_join_ret;
	response["ret"] = ::common::SUCCEED;
	response["unionId"] = 0;

	int32_t count = 0;
	const CGuildManager::TGuildRankVec& guildrank = CGuildManager::GetInstance().guild_rank_vec();
	for (int32_t i = 0; i < guildrank.size(); ++i )
	{
		CGuild* guild = CGuildManager::GetInstance().GetGuildByID(guildrank[i]);
		if (guild == NULL )
		{
			continue;
		}
		if (guild->IsGuildFull())
		{
			continue;
		}
		if (player.GetLevel() < guild->minlimitlv())
		{
			continue;
		}
		if ( guild->auto_join() && !guild->IsGuildFull())
		{
			int32_t ret_code = CGuildManager::GetInstance().autoApply(*guild, player.GetPlayerId());
			if (ret_code == ::common::SUCCEED)
			{
				// 成功了直接就退出了，失败了，还是走申请逻辑吧
				return;
			}
		}
		int32_t ret_code = CGuildManager::GetInstance().ApplyGuild(player.GetPlayerId(), *guild);
		if (ret_code != ::common::SUCCEED)
		{
			continue;
		}
		count++;
		if (count >= 20)
		{
			break;
		}
	}
	Json::Value auj;
	CGuildManager::GetInstance().GetPlayerApplyList(auj, player.GetPlayerId());
	response["auj"] = auj;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_application_join_ret);
}

int32_t CUnionModule::CanPlayerJoinUnionCD(int32_t playerid)
{
	//判断创建公会CD
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerid);
	if (playerinfo == NULL)
	{
		return ::common::ERR_GUILD_PLAYERINFO_ERR;
	}
	if (playerinfo->PlayerGuild().leave_guild_time() != 0 && playerinfo->PlayerGuild().GetJoinCDLimitTime() > CUR_SEC)
	{
		return ::common::ERR_GUILD_JOIN_UNION_CD;
	}
	return ::common::SUCCEED;
}

void CUnionModule::queryUnionJournalListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t start = m_jv["arg2"].asInt();
	int32_t count = m_jv["arg3"].asInt();

	Json::Value response;
	response["msgid"] = union_query_journal_list_ret;
	response["ret"] = ::common::SUCCEED;
	
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_journal_list_ret);
		return;
	}
	Json::Value guildlog;
	guild->FillGuildLog(guildlog);
	response["item"] = guildlog;

	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_journal_list_ret);
}

void CUnionModule::PlayerEnterUnionBossRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	Json::Value herojson = m_jv["hero"];

	int32_t boss_activityid = CGuildManager::GetInstance().GetGuildBossActivityID();

	Json::Value response;
	response["msgid"] = union_enter_boss_response;
	response["ret"] = ::common::SUCCEED;
	//判断公会boss是否开启
	bool isopen = CActivityModule::GetInstance().IsActivityOpen(boss_activityid);
	if ( !isopen )
	{
		response["ret"] = ::common::ERR_GUILD_BOSS_ISNOTOPEN;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_enter_boss_response);
		return;
	}
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL )
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_enter_boss_response);
		return;
	}
	// 判断玩家今天活动次数够不够
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(boss_activityid);
	if ( acvitytpl == NULL )
	{
		LOG_ERROR("default", "guild boss activitytpl is null[%d]", boss_activityid);
		return;
	}
	if ( player.role_activity().GetJoinTimes(boss_activityid) >= acvitytpl->join_time())
	{
		response["ret"] = ::common::ERR_GUILD_COUNT_LESS;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_enter_boss_response);
		return;
	}
	// ....
	// 判断boss是否还活着
	if (guild->GetGuildBoss().isDie())
	{
		response["ret"] = ::common::ERR_GUILD_BOSS_ISDIE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_enter_boss_response);
		return;
	}
	// 扣次数，进去打
	player.role_activity().AddJoinTime(boss_activityid);

	// 去lua获取英雄数据
	std::string herostr = JsonWriter(herojson);
	char heroattrib[100 * 1024] = { 0 };
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunctionWithRet(LUA_UnionManagerScript,
		LUA_GetHeroAttrib, player.GetPlayerId(), herostr.c_str(), heroattrib);

	guild->GetGuildBoss().PlayerEnterBoss(player.GetPlayerId());
	CGuildManager::GetInstance().GuildEnterBoss(*guild);

	response["maxhp"] = (double)guild->GetGuildBoss().boss_maxhp();
	response["curhp"] = (double)guild->GetGuildBoss().boss_curhp();
	Json::Value hero; 
	std::string heroattrib_str(heroattrib);
	JsonReader(heroattrib_str, hero);

	response["hero"] = hero["hero"];
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_enter_boss_response);
}

void CUnionModule::PlayerDamageReport(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t damage = m_jv["damage"].asInt();
	bool isdie = m_jv["die"].asBool();

	// 伤害范围判断
	PlayerLevelUp* levelup_cfg = PlayerLevelUpCacheData::GetInstance().GetData(player.GetLevel());
	if ( levelup_cfg == NULL )
	{
		LOG_ERROR("default", "player levelup config is null, playerid[%d] level[%d]", player.GetPlayerId(), player.GetLevel());
		return;
	}
	if ( damage > levelup_cfg->mdpslimit || damage <= 0 )
	{
		LOG_ERROR("default", "player[%d] report damage[%d] is too max!!!", player.GetPlayerId(), damage);
		return;
	}

	bool isopen = CActivityModule::GetInstance().IsActivityOpen(2);
	if (!isopen)
	{
		LOG_ERROR("default", "player[%d] report damage[%d] activity end!!!", player.GetPlayerId(), damage);
		return;
	}
	
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if ( guild == NULL )
	{
		return;
	}

	// boss减血，判断血量是否死亡
	// 如果死亡，立即广播给公会的人

	guild->GetGuildBoss().AddPlayerDamage(player.GetPlayerId(), damage, isdie);
}

void CUnionModule::UnionBossInfoRequest(Player& player, const CJsonMessageBase& msg)
{
	Json::Value response;
	response["msgid"] = union_boss_info_response;
	response["ret"] = ::common::SUCCEED;

	int32_t boss_activityid = CGuildManager::GetInstance().GetGuildBossActivityID();
	// 判断玩家今天活动次数够不够
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(boss_activityid);
	if (acvitytpl == NULL)
	{
		response["ret"] = ::common::ERR_GUILD_UNION_ACTIVITY_CFG_ERR;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_boss_info_response);
		LOG_ERROR("default", "guild boss activitytpl is null[%d]", boss_activityid);
		return;
	}

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_boss_info_response);
		return;
	}
	response["maxhp"] = (double)guild->GetGuildBoss().boss_maxhp();
	response["curhp"] = (double)guild->GetGuildBoss().boss_curhp();
	response["bossid"] = guild->GetGuildBoss().boss_id();
	response["level"] = guild->GetGuildBoss().boss_lv();
	Json::Value ranklist;
	guild->GetGuildBoss().FillDamageRank(ranklist);
	response["ranklist"] = ranklist;
	response["count"] = player.role_activity().GetJoinTimes(boss_activityid);
	response["maxcount"] = acvitytpl->join_time();
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_boss_info_response);
}

void CUnionModule::OnPlayerEnterGame(Player& player)
{
	int32_t guildbossid = CGuildManager::GetInstance().GetGuildBossActivityID();
	bool isopen = CActivityModule::GetInstance().IsActivityOpen(guildbossid);
	if (isopen) {
		Json::Value notify;
		notify["start"] = 1;
		notify["msgid"] = union_boss_start_notify;
		std::string sendstr = JsonWriter(notify);
		player.SendToClient(&sendstr, union_boss_start_notify);
	}

}

void CGuildBossNotify::TimerActive()
{
	CGuildManager::GetInstance().GuildBossNotify();
	TimerStart();
}

void CUnionModule::QueryUnionAlcoholList(Player& player, const CJsonMessageBase& msg)
{
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == nullptr)
	{
		LOG_ERROR("default", "guild is empty playerId[%d]", player.GetPlayerId());
		return;
	}
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild->get_guilde_lv());

	std::unordered_map<int32_t, CUnionAlcohol> union_alcohol_list = guild->GetAlcohols();

	Json::Value stable;
	int i = 0;

	CGuildMember* member = guild->GetMember(player.GetPlayerId());
	if (member == NULL)
	{
		LOG_ERROR("default", "guildmember is empty playerId[%d]", player.GetPlayerId());
		return ;
	}
	int32_t alcohol_expire = member->get_alcohol_expire();
	int32_t alcohol_id = member->get_alcohol_id();

	for (auto it = union_alcohol_list.begin(); it != union_alcohol_list.end(); ++it) {
		

		Json::Value item;
		item["skill_id"] = (it->second).skill_id;
		item["expire"] = 0;//喝酒使用时间，非是过期结束的时间
		item["con_time"] = (it->second).con_time;
		item["alcohol_id"] = it->first;

		if (alcohol_id == it->first) {
			item["expire"] = (CUR_SEC - alcohol_expire) < (it->second).con_time ? alcohol_expire :0 ;
		}
		
		stable[i++] = item;
	}

	Json::Value target;
	target["data"] = stable;
	target["msgid"] = union_alcohol_list_ret;
	target["alcohol_count"] = member->get_alcohol_count();
	target["ret"] = ::common::SUCCEED;
	player.SendToClient(target, union_alcohol_list_ret);
}

void CUnionModule::UseUnionAlcohol(Player& player, const CJsonMessageBase& msg)
{
	Json::Value jv = msg.GetJsonValue();
	int32_t alcohol_id = jv["alcohol_id"].asInt();
	const CUnionAlcohol* union_alcohol = CTPLManager::GetInstance().GetUnionAlcoholByID(alcohol_id);

	if (union_alcohol == nullptr) {
		LOG_ERROR("default", "the union not has the alcohol id[%d]", alcohol_id);
		return;
	}

	Json::Value target;
	target["msgid"] = union_alcohol_use_ret;
	target["ret"] = ::common::SUCCEED;

	// 消耗
	int32_t ret_code = CGuildAlcoholLogic::ReduceCurrency(player, *union_alcohol);
	if (ret_code != ::common::SUCCEED) {
		target["ret"] = ret_code;
		player.SendToClient(target, union_alcohol_use_ret);
		return;
	}

	// 公会酒品使用
	ret_code = CGuildAlcoholLogic::SaveAlcoholMembers(player, *union_alcohol, target);
	if (ret_code != ::common::SUCCEED)
	{
		target["ret"] = ret_code;
		player.SendToClient(target, union_alcohol_use_ret);
		return;
	}

	// 作用被动技能给Player 非英雄
	PassivitySkill& skill = player.passivity_skill();
	ret_code = skill.UpdateSkill(union_alcohol->skill_id, CUR_SEC, union_alcohol->con_time);
	if (ret_code != ::common::SUCCEED)
	{
		target["ret"] = ret_code;
		player.SendToClient(target, union_alcohol_use_ret);
	}

	// 发送使用后的酒品技能
	//skill.UpdateSkill(union_alcohol->skill_id, CUR_SEC, union_alcohol->con_time);
	Json::Value skill_data;
	skill_data["skill_id"] = union_alcohol->skill_id;
	skill_data["expires"] = (int32_t)CUR_SEC;
	skill_data["con_time"] = union_alcohol->con_time;
	skill_data["alcohol_id"] = alcohol_id;
	target["alcohol"] = skill_data;
	player.SendToClient(target, union_alcohol_use_ret);
}

void CUnionModule::queryUnionRedpacketListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t type = m_jv["type"].asInt();

	Json::Value response;
	response["msgid"] = union_query_redpacket_list_ret;
	response["ret"] = ::common::SUCCEED;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		response["ret"] = ::common::ERR_NOT_JOINED_UNION;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_query_redpacket_list_ret);
		return;
	}

	response["type"] = type;

	Json::Value redpacketlist_json;
	redpacketlist_json.clear();
	guild->FillRedpacketList(player.GetPlayerId(), type, redpacketlist_json);

	response["list"] = redpacketlist_json;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_redpacket_list_ret);
}

void CUnionModule::playerGetRedpacketRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t redpacketId = m_jv["id"].asInt();

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		return;
	}
	CUnionRepacket kCUnionRepacket = guild->GetUnionRepacketById(redpacketId);
	if (kCUnionRepacket.m_idx == 0)
	{
		return;
	}

	UnionRedpacketInfo kUnionRedpacketInfo = UnionRedpacketTableMgrPtr->GetUnionRedpacketInfoById(kCUnionRepacket.m_tId);
	if (kUnionRedpacketInfo.m_id == 0)
	{
		LOG_ERROR("default", "union redpacket is null id = %d", kCUnionRepacket.m_idx);
		return;
	}

	// 是否已经领取过
	if (guild->ExsitGetRepacketRewardByPlayerId(kCUnionRepacket.m_idx, player.GetUnionId()))
	{
		return;
	}

	// 保证剩下的人至少每人1个
	//int32_t itemCount = 0;
	int32_t itemCount = RAND(kCUnionRepacket.m_remainItemCount - (kUnionRedpacketInfo.m_allCount - kCUnionRepacket.m_getCount - 1));


	kCUnionRepacket.m_remainItemCount = kCUnionRepacket.m_remainItemCount - itemCount;
	kCUnionRepacket.m_getCount = kCUnionRepacket.m_getCount + 1;

	CUnionRepacketInfo kCUnionRepacketInfo;
	kCUnionRepacketInfo.m_playerId = player.GetPlayerId();
	kCUnionRepacketInfo.m_getTime = CUR_SEC;
	kCUnionRepacketInfo.m_getnum = itemCount;
	kCUnionRepacketInfo.m_name = player.GetName();
	kCUnionRepacket.m_list[kCUnionRepacketInfo.m_playerId] = kCUnionRepacketInfo;

	guild->UpdateRedpacket(kCUnionRepacket);


	Json::Value itemlist;
	Json::Value oneitem;
	oneitem["id"] = kUnionRedpacketInfo.m_redPacketItemId;
	oneitem["at"] = itemCount;
	itemlist.append(oneitem);
	std::string str = JsonWriter(itemlist);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerManagerScript,
		LUA_ExtendItemToPlayerBackPack, player.GetPlayerId(), (double)player.GetAccount(), str.c_str());

	Json::Value response;
	response["msgid"] = union_get_redpacket_ret;
	response["ret"] = ::common::SUCCEED;

	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_get_redpacket_ret);
}

void CUnionModule::queryUnionRedpacketInfoRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t redpacketId = m_jv["id"].asInt();

	Json::Value response;
	response["msgid"] = union_query_redpacket_info_ret;
	response["ret"] = ::common::SUCCEED;
	response["id"] = redpacketId;

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		return;
	}
	CUnionRepacket kCUnionRepacket = guild->GetUnionRepacketById(redpacketId);
	if (kCUnionRepacket.m_idx == 0)
	{
		return;
	}

	response["tId"] = kCUnionRepacket.m_tId;
	response["getnum"] = kCUnionRepacket.m_getCount;

	Json::Value list_json;
	for (TUnionRepacketInfoMap::iterator it = kCUnionRepacket.m_list.begin(); it != kCUnionRepacket.m_list.end(); ++it)
	{
		Json::Value oneInfo;
		oneInfo["getTime"] = it->second.m_getTime;
		oneInfo["getnum"] = it->second.m_getnum;
		oneInfo["name"] = it->second.m_name;
		oneInfo["playerId"] = it->second.m_playerId;
		list_json.append(oneInfo);
	}
	response["list"] = list_json;

	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, union_query_redpacket_info_ret);
}

void CUnionModule::playerSendRedpacketRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t tId = m_jv["tId"].asInt();

	UnionRedpacketInfo kUnionRedpacketInfo = UnionRedpacketTableMgrPtr->GetUnionRedpacketInfoById(tId);
	if (kUnionRedpacketInfo.m_id == 0)
	{
		LOG_ERROR("default", "union redpacket is null tId = %d", tId);
		return;
	}

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		return;
	}

	Json::Value response;
	response["msgid"] = union_send_redpacket_ret;
	response["ret"] = ::common::SUCCEED;

	// 条件不足
	if (player.GetCurrency(Fixed1024::CURRENCY_TICKET) < kUnionRedpacketInfo.m_consumeItemCount)
	{
		response["ret"] = ::common::ERR_GUILD_UNION_SENDREPACKET_DIAMOND_ERR;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, union_send_redpacket_ret);
		return;
	}

	// 先扣钱在说
	player.SetCurrency(Fixed1024::CURRENCY_TICKET, (player.GetCurrency(Fixed1024::CURRENCY_TICKET) - kUnionRedpacketInfo.m_consumeItemCount));
	player.SetPlayerSomeInfoToRedisDB("ticket", player.GetCurrency(Fixed1024::CURRENCY_TICKET));

	Json::Value redpacketrewarld;
	redpacketrewarld.clear();
	UnionRedpacketTableMgrPtr->GetRewardJsonItem(tId, redpacketrewarld);

	std::string str = JsonWriter(redpacketrewarld);
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerManagerScript,
		LUA_ExtendItemToPlayerBackPack, player.GetPlayerId(), (double)player.GetAccount(), str.c_str());

	int32_t idx = CGuildManager::GetInstance().GetRedpacketIdMax() + 1;
	CGuildManager::GetInstance().SetRedpacketIdMax(idx);

	CUnionRepacket kCUnionRepacket;
	kCUnionRepacket.m_idx = idx;
	kCUnionRepacket.m_unionId = player.GetUnionId();
	kCUnionRepacket.m_playerId = player.GetPlayerId();
	kCUnionRepacket.m_name = player.GetName();
	kCUnionRepacket.m_sendTime = CUR_SEC;
	kCUnionRepacket.m_tId = tId;
	kCUnionRepacket.m_remainItemCount = kUnionRedpacketInfo.m_redPacketItemCount;
	kCUnionRepacket.m_getCount = 0;
	kCUnionRepacket.m_createTime = CUR_SEC;
	guild->UpdateRedpacket(kCUnionRepacket);

	int32_t msgid = union_send_redpacket_ret;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, msgid);
}